/**
 * Created by GanJc on 2015/9/10.
 */

'use strict';

function getPrice() {
    var js = document.getElementById('jsnode');
    if(js){
        js.remove();
    }
    js = document.createElement('script');
    js.id ='jsnode';
    js.src = 'http://api.money.126.net/data/feed/0000001,1399001?callback=refreshPrice';
    document.getElementsByTagName('head')[0].appendChild(js);
}

function refreshPrice(data) {
    var p = document.getElementById('test-jsonp');
    p.innerHTML = '当前价格：' +
    data['0000001'].name +': ' +
    data['0000001'].price + '；' +
    data['1399001'].name + ': ' +
    data['1399001'].price;
}

function callback() {
    console.log('Done');
}
console.log('before setTimeout()');
setTimeout(callback, 1000); // 1秒钟后调用callback函数
//setInterval(callback, 1000); // 1秒钟后调用callback函数
console.log('after setTimeout()');
//new Promise
//new Promise(function () {});

//function test(resolve, reject) {
//    var timeOut = Math.random() * 2;
//    console.log('set timeout to: ' + timeOut + ' seconds.');
//    setTimeout(function () {
//        if (timeOut < 1) {
//            console.log('call resolve()...');
//            resolve('200 OK');
//        }
//        else {
//            console.log('call reject()...');
//            reject('timeout in ' + timeOut + ' seconds.');
//        }
//    }, timeOut * 1000);
//}
//
//new Promise(test).then(function (result) {
//    console.log('成功：' + result);
//}).catch(function (reason) {
//    console.log('失败：' + reason);
//});

new Promise(function (resolve, reject) {
    console.log('start new Promise...');
    var timeOut = Math.random() * 2;
    console.log('set timeout to: ' + timeOut + ' seconds.');
    setTimeout(function () {
        if (timeOut < 1) {
            console.log('call resolve()...');
            resolve('200 OK');
        }
        else {
            console.log('call reject()...');
            reject('timeout in ' + timeOut + ' seconds.');
        }
    }, timeOut * 1000);
}).then(function (r) {
        console.log('Done: ' + r);
    }).catch(function (reason) {
        console.log('Failed: ' + reason);
    });


var p1 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 600, 'P2');
});
// 同时执行p1和p2，并在它们都完成后执行then:
Promise.all([p1, p2]).then(function (results) {
    console.log(results); // 获得一个Array: ['P1', 'P2']
});
